package com.itheima.reggie.controller;

import com.itheima.reggie.config.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired(required = false)
    private AddressBookService addressBookService;


    /**
     * 新增用户
     * http://localhost:8080/addressBook
     */
    @PostMapping
    public R<String> adduser(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBook.setCreateUser(userId);
        addressBook.setUpdateUser(userId);
        addressBookService.addUser(addressBook);
        return R.success("添加成功");
    }
    /**
     * 查询
     * @return
     */
    @GetMapping("/list")
    public R<List> list(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        List<AddressBook>addressBookList= addressBookService.findAll(userId);
      return R.success(addressBookList);
    }
    /**
     * http://localhost:8080/addressBook/1417414526093082626
     * 数据回显
     */
    @GetMapping("/{id}")
    public R<AddressBook> show(@PathVariable Long id){
     AddressBook addressBook= addressBookService.findById(id);
        return R.success(addressBook);
    }
    @PutMapping("/default")
    public R<String> updateDefault(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBookService.update(addressBook);
        return R.success("修改默认成功");
    }
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUpdateUser(userId);
        addressBookService.updateAll(addressBook);
        return R.success("修改默认成功");
    }
    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault(HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);

        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }
}
